/* 
 * 放在产品价格下面
 */
public with sharing class ProductPriceController {
    
    public List<PriceBean> pbList { get; set; }

    public Price__c price{get;set;} 
    
    public String pId{ get; private set; } //产品id 

    public String msg {get;set;}
    public Boolean isSuccess {get;set;}
    
    public ProductPriceController (ApexPages.StandardController controller) {
        pId = System.currentPageReference().getParameters().get('pid');
    }
    
    public void init() {
        pbList= new List<PriceBean>();
        price=new Price__c();
        price.Product__c=pId;
        
        ///获取所有公司的价格，放在List<PriceBean> pbList
        pbList.clear();
        
        List<Price__c> plist = Database.query(this.soqlStr() + ' and Product__c=:pId');

        Map<String,object> cm = getPicklistValues('Price__c','Company__c');
        Set<String> companys=cm.keySet();
        for(String company:companys){
            PriceBean pb=new PriceBean ();
            Price__c p=new Price__c();
            p.Product__c=price.Product__c;
            pb.rec=p;
            pb.rec.Company__c=company;
            pb.chk=false;
            
            for (Price__c p0 : plist) {
                if(p0.Company__c==company){
                    pb.rec=p0;
                    pb.chk=true;
                }
            }
            pbList.add(pb);
            
        }

    }
    
    //保存
    public void save() {
        Savepoint sp = Database.setSavepoint();
        pId=price.Product__c;
        msg = '';
        try {
            //删除该产品下所有的价格
            List<Price__c> delList = [select Id from Price__c where Product__c= :pId];
            if (delList.size() > 0) delete delList;
            
            // 插入已选择的物品
            if (pbList.size() > 0) {
                List<Price__c> insList = new List<Price__c>();
                for (PriceBean pb : pbList) {
                    if(pb.chk){
                       insList.add(
                        new Price__c(
                            //这里Product使用的是头上用户选择的产品
                            Product__c=pId,//pb.rec.Product__c,//产品.
                            MarketPrice__c=pb.rec.MarketPrice__c,//市场报价
                            // HospitalSalesPrice__c=pb.rec.HospitalSalesPrice__c,//医院销售价(销售权限)
                            AreaDealerPrice__c=pb.rec.AreaDealerPrice__c,//区域经销商价
                            InvoiceDealerPrice__c=pb.rec.InvoiceDealerPrice__c,//报单经销商价
                           // HospitalBottomPrice__c=pb.rec.HospitalBottomPrice__c,//医院销售底价
                            HospitalManagerPrice__c=pb.rec.HospitalManagerPrice__c,//医院销售价(经理/主管)
                            RepairCost__c=pb.rec.RepairCost__c,//保修成本
                            InstCost__c=pb.rec.InstCost__c,//成本价
                            LastExecutePrice__c=pb.rec.LastExecutePrice__c,//   上次执行价格
                            Company__c=pb.rec.Company__c ,//公司
                            Taxrate__c = pb.rec.Taxrate__c,
                            GroupRegionalDistributorsPrice__c = pb.rec.GroupRegionalDistributorsPrice__c,
                            GroupMarketPrice__c = pb.rec.GroupMarketPrice__c,
                            GroupDeclarationDealerPrice__c = pb.rec.GroupDeclarationDealerPrice__c,
                            GroupTerminalGuidePrice__c = pb.rec.GroupTerminalGuidePrice__c,
                            Subsidiary_price__c = pb.rec.Subsidiary_price__c

                        )
                      );
                    }
                }
                
                insert insList;
                isSuccess = true;
               
            }
             msg = '保存成功!';
          //  ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, System.Label.Save_OK));
        } catch (Exception e) {
            isSuccess = false;
            Database.rollback(sp);
            msg  = '保存失败:'+ e.getMessage();
            //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, e.getMessage()));
        } 
    }
    
    private String soqlStr() {
        Schema.DescribeSobjectResult m = Price__c.sObjectType.getDescribe();
        Map<String, Schema.SObjectField> fieldMap = m.fields.getMap();
        
        String sql = 'select ';
        String fields = '';
        for (String field : fieldMap.keySet()) {
            if (fields.length() > 0) {
                fields += ', '; 
            }
            fields += field;
        }
        sql += fields;
        sql += ' from Price__c where Name != null';

        return sql;
    }
   
    //获得PickList的值
    public static Map<String, object> getPicklistValues(String sObjectName, String sFieldName){
        Map<String, object> picValues= new Map<String, object>();
        Map<String, Schema.SObjectType> sObjectDescribeMap = Schema.getGlobalDescribe();
        if (sObjectDescribeMap.containsKey(sObjectName)) {
            Map<String, Schema.SobjectField> sObjectFieldsMap = 
               sObjectDescribeMap.get(sObjectName).getDescribe().fields.getMap();
            if (sObjectFieldsMap.containsKey(sFieldName)) {
                Schema.DescribeFieldResult sObjectFieldDescribe = sObjectFieldsMap.get(sFieldName).getDescribe();
                List<Schema.PicklistEntry> lPickEntryList = sObjectFieldDescribe.getPicklistValues();
                for (Schema.PicklistEntry tPicklistEntry : lPickEntryList) {
                    picValues.put(tPicklistEntry.getValue(), new Map<String,object>{
                        'value' => tPicklistEntry.getValue(),
                        'isActive' => tPicklistEntry.isActive(),
                        'isDefaultValue' => tPicklistEntry.isDefaultValue(),
                        'label' => tPicklistEntry.getLabel()
                    });
                }
            } else {
                //TODO 不存在此字段的执行
            }
        } else {
            // TODO 不存在此sObject的执行
        }
        return picValues;
    }
    
    public class PriceBean {
         public Price__c rec{get;set;}
         public Boolean chk { get; set; }
    }

}